package com.qpx.zhoukaofile.controller;


import com.qpx.zhoukaofile.entity.FileEntity;
import com.qpx.zhoukaofile.service.FileService;
import com.qpx.zhoukaofile.service.MessageService;
import com.qpx.zhoukaofile.utils.UploadUtils;
import com.zhoukao.dto.FileDto;
import com.zhoukao.dto.MessageDto;
import com.zhoukao.vo.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.transform.Result;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class FileController {

    @Autowired
    FileService fileService;

    @Autowired
    UploadUtils uploadUtils;

    @Autowired
    MessageService messageService;
    /**
     * 图片上传
     * @return
     */
    @RequestMapping("/file/upload")
    public ResultEntity upload(@ModelAttribute FileDto fileDto) throws IOException {

        //第一步 多图片上传
        List<String> uploadList = uploadUtils.upload(fileDto.getFiles());


        //第二步  调用message 接口保存消息  ,返回 messageID
        MessageDto messageDto = new MessageDto();
        BeanUtils.copyProperties(fileDto,messageDto);
        ResultEntity result = messageService.save(messageDto);
        int mid = (int)result.getObj();

        //第三步  根据messageID 组装file 实体 进行保存
        List<FileDto> fileDtos = new ArrayList<>();
        for (String s : uploadList) {
            FileDto fileDto1 = new FileDto();
            fileDto1.setMid(mid);
            fileDto1.setPics(s);
            fileDtos.add(fileDto1);
        }
        fileService.save(fileDtos);

        return ResultEntity.ok();
    }

    @RequestMapping("/file/getFileByMid")
    public ResultEntity  getFileByMid( Integer mid){
        List<FileEntity> fileByMid = fileService.findFileByMid(mid);
        return ResultEntity.ok("200","查询成功",fileByMid);
    }

    @RequestMapping("/file/delFileByID")
    public ResultEntity delFileByID(String ids){
        String[] split = ids.split(",");
        fileService.delFileByID(Arrays.asList(split));
        return ResultEntity.ok();
    }
    @RequestMapping("/file/delFileByMID")
    public ResultEntity delFileByMid(@RequestBody String mids){
        String[] split = mids.split(",");
        fileService.delFileByMID(Arrays.asList(split));
        return ResultEntity.ok();
    }

}
